package org.atlantis.grosbeak.logger.adapter;

import org.atlantis.grosbeak.logger.Logger;
import org.atlantis.grosbeak.logger.LoggerAdapter;
import org.atlantis.grosbeak.plugin.Plugin;

/**
 * Log4j适配器。<br>
 * 判断Log4j是否可使用的途径：
 * <ol>
 * <li>如果CurrentThread的ContextClassLoader能够加载
 * <code>org.apache.log4j.Logger</code>，那么就认为Log4j可使用。</li>
 * <li>如果系统属性log4j.defaultinitOverride不为空、为true，那么认为Log4j不可使用。</li>
 * <li>如果系统属性log4j.configuration非空，则认为Log4j可以使用。</li>
 * <li>根据Log4j的判断去查找log4j.xml或log4j.properties，如果能查找到，则认为Log4j可使用。</li>
 * </ol>
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class Log4jAdapter implements LoggerAdapter, Plugin {

	public Logger getLogger(String className) {
		return new Log4jLogger(className);
	}

	public boolean canWork() {
		try {
			Class.forName("org.apache.log4j.Logger", true, Thread
					.currentThread().getContextClassLoader());
		} catch (ClassNotFoundException e) {
			return false;
		}
		return isConfigured();
	}

	// Log4j是否被配置过
	private boolean isConfigured() {
		String configureVal = System.getProperty("log4j.defaultInitOverride");

		if (configureVal != null && "true".equalsIgnoreCase(configureVal))
			return false;

		if (System.getProperty("log4j.configuration") != null)
			return true;

		if (hasConfigurationFile("log4j.properties"))
			return true;
		return hasConfigurationFile("log4j.xml");
	}

	// 是否存在Log4j的配置文件
	private boolean hasConfigurationFile(String resourceName) {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		if (loader.getResource(resourceName) != null)
			return true;
		loader = getClass().getClassLoader();
		if (loader.getResource(resourceName) != null)
			return true;
		return (ClassLoader.getSystemResource(resourceName) != null);
	}
}
